package org.example.datascreen.service.Impl;

import okhttp3.*;
import org.example.datascreen.configuration.FboxConfig;
import org.example.datascreen.configuration.YingshiConfig;
import org.example.datascreen.eneity.CameraData;
import org.example.datascreen.eneity.Device;
import org.example.datascreen.repository.CameraDataRespository;
import org.example.datascreen.repository.DeviceRespository;
import org.example.datascreen.service.DataService;
import org.example.datascreen.service.TokenService;
import org.example.datascreen.utils.AliOssUtil;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class DataServiceImpl implements DataService {

    @Autowired
    private FboxConfig fboxConfig;
    @Autowired
    private YingshiConfig yingshiConfig;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private DeviceRespository deviceRespository;
    @Autowired
    private SensorDataserviceImpl sensorDataservice;
    @Autowired
    private CameraDataRespository cameraDataRespository;

    @Scheduled(cron = "0 30 12 * * ?")//每天12:30执行一次
    @Override
    public void getSensorData() {
        int maxRetries = 2;
        int retryCount = 0;
//        fboxConfig.setToken("eyJhbGciOiJSUzI1NiIsImtpZCI6Ijg2QzQ2RTIxQTc0MTUxNTFCOTQ0MTY4MzhEMERGODU1OTZENkM2RTgiLCJ0eXAiOiJhdCtqd3QiLCJ4NXQiOiJoc1J1SWFkQlVWRzVSQmFEalEzNFZaYld4dWcifQ.eyJuYmYiOjE3MzYyNTUyODgsImV4cCI6MTczNjI2MjQ4OCwiaXNzIjoiaHR0cHM6Ly9hY2NvdW50LmZsZXhlbS5jb20vY29yZSIsImF1ZCI6Imlkc3ZyMyIsImNsaWVudF9pZCI6IjY4ZGIyZThiZGE4ZDQ3YjViNWRiN2VhZjcxYzdkY2RkIiwic3ViIjoiZTcxMjRhMTYtMjEwNS00ZTU4LWI5OGItOWE2ZmFkNjZiYjA3Iiwic2NvcGUiOlsiZmJveCJdfQ.ybzO4-IAW_3AsfDmq8y_pBAmOXC52MaonD63iGCuL4krSsTKhqlm_bQJAZ9PHgt8W8yyLmal5ii1fPMYBsDBTOwtVDpHrefdYc3ByM1uK5sVDRvrJ87Dgk-V9I6F8UrLiX5CdLVKLz0H_o7pzPMqJ8E0VCQlb8-5CPE4wtCtugwLJ7fvtNp0ql_513NycFNenObNLH7d-rIS-S2t5FGIIJwCBQ49K4quOylWawrNdcq6CgWctdcdvjl0frDqXAsUoXKXIa-1QCT0qYU5Q99yFUddU8GboxS2d5bR_9_mvg-FzxDO-xQTwGUz5eStOwEflecMECh6DH-dmPZjoQ-0ww");
    
        while (retryCount <= maxRetries) {
            if (fboxConfig.getToken() == null)
                fboxConfig.setToken(tokenService.getfboxToken());
    
            OkHttpClient client = new OkHttpClient();
    
            String url = fboxConfig.getGetUrl();
             JSONObject requestBodyJson = new JSONObject();
             JSONArray ids = new JSONArray();
    
            List<String> sensorIds = deviceRespository.findSerialNumbersByCategory("Sensor");
            for (String sensorId : sensorIds) {
                ids.put(sensorId);
            }
            requestBodyJson.put("ids", ids);
    
            RequestBody requestBody = RequestBody.create(requestBodyJson.toString(), MediaType.parse("application/json"));
            Request request = new Request.Builder()
                    .url(url)
                    .addHeader("Authorization", "Bearer " + fboxConfig.getToken())
                    .post(requestBody)
                    .build();
            System.out.println(request);
    
            try (Response response = client.newCall(request).execute()) {
                if (response.code() == 401) {
                    fboxConfig.setToken(tokenService.getfboxToken());
                    retryCount++;
                    continue;
                }
    
                if (!response.isSuccessful()) {
                    throw new IOException("获取传感器数据失败: " + response);
                }
                System.out.println(response);

                JSONArray data = new JSONArray(response.body().string());
                System.out.println(data);
                for (int i = 0; i < data.length(); i++) {
                    switch (data.getJSONObject(i).getString("id")){
                        case "327061586065758006":
                            sensorDataservice.saveConductivityData(data.getJSONObject(i));
                            break;
                        case "327061586065758005":
                            sensorDataservice.saveMoistureData(data.getJSONObject(i));
                            break;
                        case "327061586065758008":
                            sensorDataservice.saveNitrogenData(data.getJSONObject(i));
                            break;
                        case "327061586065758007":
                            sensorDataservice.savePHData(data.getJSONObject(i));
                            break;
                        case "327061586065758015":
                            sensorDataservice.saveTemperatureData(data.getJSONObject(i));
                            break;
                    }
                }
                return; // 请求成功，退出方法
            } catch (IOException e) {
                if (retryCount >= maxRetries) {
                    throw new RuntimeException("获取传感器数据失败", e);
                }
                retryCount++;
            }
        }
    }
    @Scheduled(fixedRate = 30 * 60 * 1000) // 每30分钟执行一次
    @Override
    public void getPhoto() {
        int maxRetries = 2;
        int retryCount = 0;

        while (retryCount < maxRetries) {
            if (yingshiConfig.getToken() == null)
                yingshiConfig.setToken(tokenService.getyingshiToken());

            OkHttpClient client = new OkHttpClient();

            String url = yingshiConfig.getGetUrl();

            FormBody formBody = new FormBody.Builder()
                    .add("accessToken", yingshiConfig.getToken())
                    .add("deviceSerial", yingshiConfig.getDeviceSeria())
                    .add("channelNo", yingshiConfig.getChannelNo())
                    .add("quality", yingshiConfig.getQuality())
                    .build();

            Request request = new Request.Builder()
                    .url(url)
                    .post(formBody)
                    .build();
            System.out.println(request);

            try (Response response = client.newCall(request).execute()) {
                if (response.code() == 401) {
                    yingshiConfig.setToken(tokenService.getyingshiToken());
                    retryCount++;
                    continue;
                }

                if (!response.isSuccessful()) {
                    throw new IOException("获取照片失败: " + response);
                }
                System.out.println(response);

                JSONObject data = new JSONObject(response.body().string());
                String picUrl = data.getJSONObject("data").getString("picUrl");
                System.out.println(picUrl);

                InputStream in = AliOssUtil.getFileInputStream(picUrl);
                String uuid = UUID.randomUUID().toString();
                long timestamp = System.currentTimeMillis();
                String picName = uuid + "_" + timestamp + ".jpg";
                String ossUrl = AliOssUtil.uploadFile(picName, in);

                CameraData cameraData = new CameraData();
                cameraData.setCreatedTime(new Date());
                cameraData.setPhotoURL(ossUrl);

                Device device = new Device();
                device.setId(5L);
                cameraData.setDevice(device);
                cameraDataRespository.save(cameraData);
                return; // 请求成功，退出方法
            } catch (IOException e) {
                if (retryCount >= maxRetries) {
                    throw new RuntimeException("获取照片失败", e);
                }
                retryCount++;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }
    }
}
